﻿using mars_server.csharp.cache;
using mars_server.csharp.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace mars_server.csharp.socket
{

    public class ServerSocket
    {
        private ServerSocket() { }
        private static readonly ServerSocket instance = new ServerSocket();
        public static ServerSocket Instance
        {
            get
            {
                return instance;
            }
        }

        private string serverIp = XmlUtil.GetXmlNodeValue("ipaddress").Trim();

        private int serverPort = int.Parse(XmlUtil.GetXmlNodeValue("port").Trim());

        TcpListener tcpListener;

        //初始化TcpServer对象
        public void initSocketLisetener()
        {
            try
            {
                Console.WriteLine("||======开启TCP线程=======||");
                tcpListener = new TcpListener(IPAddress.Parse(serverIp), serverPort);
                tcpListener.Start();
                ListenClientConnect();//开启客户端同步
            }
            catch(Exception e)
            {
                Console.WriteLine("[error]--"+e.ToString());
            }
        }

        //开启监听
        public void ListenClientConnect()
        {
            TcpClient newClient = null;
            while (true)
            {
                try
                {
                    Console.WriteLine("[info]---开始监听端口【" + serverPort+"】-----------");
                    newClient = tcpListener.AcceptTcpClient();
                    UserSocket userSocket = new UserSocket(newClient);
                    UserSocketCache.UserSocketList.Add(userSocket);
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
         
        }

            
    }
}
